package com.kfm.servlet;

import com.kfm.utils.Constant;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 文件下载
        // 告诉浏览器响应的是二进制流
        resp.setContentType("application/octet-stream");
        // 获取本次请求要下载的文件名
        String name = req.getParameter("file");
        // 设置以附件的形式下载，指定下载的名字是文件原来的名字 中文名称在一行会报错 对于中文名称进行编码
        resp.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(name, StandardCharsets.UTF_8));
        File file = new File(Constant.UPLOAD_PATH + File.separator + name);
        ServletOutputStream outputStream = resp.getOutputStream();
        FileInputStream in = new FileInputStream(file);
        in.transferTo(outputStream);
        outputStream.flush();
        outputStream.close();
        in.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
